package com.caipu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caipu.entity.UserInfo;
import com.caipu.redis.RedisUtils;
import com.caipu.service.UserInfoService;
import constant.ResultConstant;
import entity.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import utils.HttpClientUtils;
import utils.JwtUtils;
import utils.TimeUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/login")
@Slf4j
public class LoginController {
    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("/token")
    @ResponseBody
    public ResultBean getTokent(@RequestBody String string) {
        try {
            JSONObject jsonObjectCode = JSON.parseObject(string);
            Map<String,Object> requestUrlParam = new HashMap<>(16);
            //开发者设置中的appId
            requestUrlParam.put("appid", ResultConstant.WeCath.APPID);
            //开发者设置中的appSecret
            requestUrlParam.put("secret", ResultConstant.WeCath.SECRET);
            //小程序调用wx.login返回的code
            requestUrlParam.put("js_code", jsonObjectCode.getString("code"));
            requestUrlParam.put("grant_type", ResultConstant.WeCath.GRANT_TYPE);
            String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
            String resultString = HttpClientUtils.doGet(requestUrl,requestUrlParam);
            log.info("resultString==>"+resultString);
            JSONObject resultJson = JSONObject.parseObject(resultString);
            String token = JwtUtils.sign(resultJson.getString("openid"),resultJson.getString("session_key"));

            JSONObject tokenObject = new JSONObject();
            tokenObject.put("token",token);
            redisUtils.set("user:token:"+resultJson.getString("openid"),token,ResultConstant.Code.TOEKN_REDIS);
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("open_id",resultJson.getString("openid"));
            UserInfo userInfo = userInfoService.getOne(queryWrapper);
            if (Objects.isNull(userInfo)){
                UserInfo userInfo1 = new UserInfo();
                userInfo1.setAvatarUrl(jsonObjectCode.getString("avatarUrl"));
                userInfo1.setCreatTime(TimeUtils.GetNowDate("yyyy-MM-dd HH:mm:ss"));
                userInfo1.setNickName(jsonObjectCode.getString("nickName"));
                userInfo1.setOpenId(resultJson.getString("openid"));
                userInfo1.setSessionKey(resultJson.getString("session_key"));
                userInfo1.setSex(Integer.parseInt(jsonObjectCode.getString("gender")));
                userInfoService.save(userInfo1);
            }
            return new ResultBean(ResultConstant.Code.SUCCESS,"token生成成功",tokenObject);

        }catch (Exception e){
            log.error("token生成失败",e);
            return new ResultBean(ResultConstant.Code.TOKEN_IS_NULL,"token生成失败");
        }

    }

    @RequestMapping("/testtoken")
    @ResponseBody
    public ResultBean testToken(@RequestBody String token) {
        JSONObject jsonObject = JSON.parseObject(token);
        boolean falg = JwtUtils.verify(jsonObject.getString("token"));
        if (falg){
            //token有效
            String opendId = JwtUtils.getOpenId(jsonObject.getString("token"));
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("open_id",opendId);
            UserInfo userInfo = userInfoService.getOne(queryWrapper);
            if (Objects.isNull(userInfo)){
                return new ResultBean(ResultConstant.Code.OPPENID_ERR,"openId错误");
            }

            Object object = redisUtils.get("user:token:"+opendId);
            if (!Objects.isNull(object)){
                //token未失效跳转小程序首页
                return new ResultBean(ResultConstant.Code.SUCCESS,"token有效");
            }else {
                return new ResultBean(ResultConstant.Code.TOKEN_NO_EXIST,"token时效失效");
            }
        }else {
            return new ResultBean(ResultConstant.Code.TOKEN_IS_NULL,"token解析失败");
        }
    }
}
